<?php

namespace App\Admin\Controllers;

use App\Admin\Actions\Grid\RowActions\BoundUserActions;
use App\Admin\Actions\Grid\RowActions\ConfirmAction;
use App\Admin\Actions\Grid\RowActions\DisPatchAction;
use App\Admin\Actions\Grid\RowActions\PayActions;
use App\Admin\Actions\Grid\RowActions\ProjectOverAction;
use App\Admin\Actions\Grid\RowActions\ProjectPerfectActions;
use App\Admin\Actions\Grid\RowActions\SendDataMessage;
use App\Admin\Actions\Grid\RowActions\SendDetailMessage;
use App\Admin\Actions\Grid\RowActions\UpdateInfoEnd;
use App\Admin\Renderable\WorkerListTable as AppWorkerListTable;
use App\Admin\Repositories\Company;
use App\Admin\Repositories\ContractTemplate;
use App\Admin\Repositories\Project;
use App\Models\AdminUser;
use App\Models\Company as AppCompany;
use App\Support\Data;
use Dcat\Admin\Admin;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Http\JsonResponse;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class ProjectController extends AdminController
{

    public function getFeeTypeValue(int $projectID, Request $request)
    {
        $projectModel = \App\Models\Project::find($projectID);
        if (empty($projectModel)) {
            return [];
        }
        $feeTypeArr = $projectModel->fee_type ? json_decode($projectModel->fee_type, true) : [];
        return $feeTypeArr[$request->input('q')] ?? '';
    }
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new Project(), function (Grid $grid) {
            // $grid->setActionClass(Grid\Displayers\DropdownActions::class);
            $grid->disableViewButton();
            // $grid->fixColumns(2, -1);
            // $grid->disablePerPages();
            // $grid->paginate(10);

            $grid->scrollbarX();
            $grid->withBorder();
            $grid->addTableClass(['table-text-center']);

            if (!Admin::user()->can('batch-delete-project')) {
                $grid->disableRowSelector();
                $grid->disableBatchDelete();
            }

            // $grid->column('id')->sortable();
            $grid->scrollbarX();
            $grid->column('project_name');
            $grid->column('project_sn');

            $grid->column('所属公司')->display(function () {
                return AppCompany::find($this->company_id)->company_name ?? '未知';
            })->label('danger');
            // $grid->column('project_code', '项目编码');
            $grid->column('active_name');
            $grid->column('company');
            // $grid->column('company_short');
            $grid->column('sponsor');
            // $grid->column('is_contract', '允许签约')
            //     ->switch();

            $grid->column('status')->using([0 => '待完结', 1 => '已完结'])->label([
                0 => 'danger',
                1 => 'success',
            ]);
            // $grid->column('fee_type');
            // $grid->column('master_user_id');
            $grid->column('master_user_id')->display(function ($userid) {
                return AdminUser::find($userid)->name ?? '';
            })->label();
            // $grid->column('master_user_name')->label();
            // $grid->column('worker_user_id');
            $grid->column('worker_user_name')->display('查看负责人')->modal(function ($modal) {
                $modal->title('查看负责人');
                return AppWorkerListTable::make(['worker_user_id' => $this->worker_user_id]);
            });
            // $grid->column('worker_user_name')->display(function ($val) {
            //     if (empty($val)) {
            //         return '';
            //     }
            //     $worker_user_name_html = '';
            //     foreach (explode(' | ', $val) as $name) {
            //         $worker_user_name_html .= '<span class="label" style="background:lightskyblue; margin-right: 5px;">' . $name . '</span>';
            //     }
            //     return $worker_user_name_html;
            // });
            $grid->column('created_at');
            // $grid->column('updated_at')->sortable();

            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('project_sn');
                // $filter->equal('project_code');
                $filter->like('project_name');
                $filter->like('active_name');
                if (Admin::user()->isAdministrator() || Admin::user()->isRole('项目经理')) {
                    $filter->equal('company_id', '所属公司')->select(AppCompany::pluck('company_name', 'id'));
                }
                $filter->like('sponsor');
                // $filter->equal('is_contract')->select([0 => '不允许签约', 1 => '允许签约']);
                $filter->equal('status')->select(Project::getStatusOptions());
            });

            /**
             * 按钮控制.
             */
            // @permissions
            if (!Admin::user()->can('project-create')) {
                $grid->disableCreateButton();
                // $grid->disableQuickCreateButton();
            }

            // @permissions
            if ((!Admin::user()->can('project-update'))) {

                $grid->disableEditButton();
                // $grid->disableQuickEditButton();
            }
            // @permissions
            if (!Admin::user()->can('project-delete')) {
                $grid->disableDeleteButton();
            }

            // 管理员和创建人可以设置分配
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $currLoginUser = auth('admin')->user();

                if (Admin::user()->isAdministrator() || $actions->row->master_user_id == $currLoginUser->id || Admin::user()->can('project-expert-list')) {
                    if ($this->status == 1) {
                        $actions->disableEdit();
                        $actions->disableDelete();
                        $actions->append('<a href="/project/user?project_id=' . $actions->row->id . '" class="text-custom" style="margin-right: 10px;"><i class="fa fa-users"></i>专家信息</a>');
                    } else {
                        // 代理人自己看自己的专家，其他角色都可以看
                        // 专家信息 区域代理人只可以看自己创建的代理人的专家

                        // append一个操作
                        $actions->append('<a href="/projectUser?project_id=' . $actions->row->id . '" class="text-custom" style="margin-right: 10px;"><i class="fa fa-users"></i>专家信息</a>');

                        // 超级管理员、内部项目经理、外部项目经理、区域管理
                        // if (Admin::user()->can('project-distribution')) {
                        //     $actions->append(new DisPatchAction()); // 分配
                        // }
                        // $actions->append('<a href="/project/disPatch/' . $actions->row->id . '/edit' . '/companyId=' . $actions->row->company_id . '" class="text-custom" style="margin-right: 10px;"><i class="fa fa-users"></i>分配</a>');

                        if (Admin::user()->can('project-distribution')) {
                            $actions->append('<a style="cursor: pointer;" class="act-aMJZRoRIMdfwCxQ2" href="/project/disPatch/' . $this->id . '/edit?companyId=' . $actions->row->company_id . '"><i class="feather icon-external-link text-custom"></i> <span class="text-custom" title="">分配</span> &emsp; </a>');
                        }


                        // 只有项目经理、超级管理员可以完结项目
                        if (Admin::user()->can('project-close')) {
                            $actions->append(new ProjectOverAction()); // 项目完结
                        }

                        if (Admin::user()->can('project-perfect')) {
                            $actions->append(new ProjectPerfectActions()); // 结算资料
                        }
                    }
                }

                // 项目更新完结
                if ($actions->row->update_info_end == 0 && Admin::user()->can('project-update-info-end')) {
                    $actions->append(new UpdateInfoEnd());
                }

            });

        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new Project(), function (Show $show) {
            $show->field('id');
            $show->field('project_name');
            $show->field('project_sn');
            $show->field('active_name');
            $show->field('sponsor');
            $show->field('company');
            $show->field('company_short');
            // $show->field('is_contract');
            $show->field('status');
            $show->field('fee_type');
            $show->field('master_user_id');
            $show->field('master_user_name');
            $show->field('worker_user_id');
            $show->field('worker_user_name');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    protected function disPatchAction($companyId)
    {
        return Form::make(new Project(), function (Form $form) {
            $form->multipleSelectTable('worker_user_id', '负责人');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new Project(), function (Form $form) {
            $form->disableViewButton();
            $form->disableViewCheck();
            $form->disableEditingCheck();
            $form->disableDeleteButton();
            $form->display('id');
            $form->select('company_id', '所属公司')
                ->options(Company::getCompanyList())
                ->required();
            $form->text('project_name')->required();
            $form->text('project_sn');
            $form->text('active_name')->required();
            $form->text('sponsor')->required();
            $form->text('company')->required();
            $form->text('company_short')->required();


            $checkBoxItem = '';
            $feeTypeOptions = [];
            if ($form->isCreating()) {
                $form->hidden('master_user_id');
                $form->hidden('master_user_name');
                $form->hidden('project_code');

                // $checkBoxItem = '';
                $feeTypeOptions = Project::getFeeTypeOptions();
                foreach ($feeTypeOptions as $feeTypeID => $feeTypeName) {
                    $checkBoxItem .= '<div class="item" style="float: left; margin-right: 10px;">
                                    <div class="vs-checkbox-con vs-checkbox-primary" style="margin-right: 16px">
                                        <input value="' . $feeTypeID . '" name="fee_type[]" class="field_fee_type _normal_ Dcat_Admin_Widgets_Checkbox" type="checkbox" initialized="" id="' . time() . $feeTypeID . '">
                                        <span class="vs-checkbox vs-checkbox-">
                                            <span class="vs-checkbox--check">
                                                <i class="vs-icon feather icon-check"></i>
                                            </span>
                                        </span>
                                        <span>' . $feeTypeName . '</span>
                                    </div>
                                    <input type="text" name="fee_type_' . $feeTypeID . '" placeholder="请输入税后金额" >
                                </div>   ';
                }
            } elseif ($form->isEditing()) { // 编辑

                // $checkBoxItem = '';
                $feeTypeArr = json_decode($form->model()->fee_type, true);

                $feeTypeOptions = Project::getFeeTypeOptions();


                foreach ($feeTypeOptions as $feeTypeID => $feeTypeName) {

                    $checkBoxItem .= '<div class="item" style="float: left; margin-right: 10px;">
                                    <div class="vs-checkbox-con vs-checkbox-primary" style="margin-right: 16px">
                                        <input value="' . $feeTypeID . '" name="fee_type[]" ' . (array_key_exists($feeTypeID, $feeTypeArr) ? 'checked' : '') . ' class="field_fee_type _normal_ Dcat_Admin_Widgets_Checkbox" type="checkbox" initialized="" id="' . time() . $feeTypeID . '">
                                        <span class="vs-checkbox vs-checkbox-">
                                            <span class="vs-checkbox--check">
                                                <i class="vs-icon feather icon-check"></i>
                                            </span>
                                        </span>
                                        <span>' . $feeTypeName . '</span>
                                    </div>
                                    <input type="text" name="fee_type_' . $feeTypeID . '" value="' . ($feeTypeArr[$feeTypeID] ?? '') . '" placeholder="请输入税后金额" >
                                </div>   ';
                }
            }
            $html = <<<HTML
        <div class="checkbox-container">
           $checkBoxItem
        </div>
        <script>
        $(function() {
            $("input[name='fee_type[]']").on('click', function () {
                if (!$(this).is(":checked")) {
                    $("input[name='fee_type_" + $(this).val() +"']").val('');
                }
            });
        });
        </script>
HTML;

            $form->html($html, '费用类型')->required();


            $form->display('created_at');
            $form->display('updated_at');

            $form->select('tpl_id', '协议模板')
                ->options(ContractTemplate::getTemplateList())
                ->required();

            $form->saving(function (Form $form) use ($feeTypeOptions) {

                foreach ($form->fee_type as $feeTypeID) {
                    if (!$form->{'fee_type_' . $feeTypeID}) {
                        return $form->response()->error('请输入' . $feeTypeOptions[$feeTypeID] . '税后金额');
                    }
                }

                if ($form->isCreating()) {
                    // 项目编码
                    $project_code = null;
                    while (true) {
                        $project_code = random_int(100000, 999999);
                        $rs = \App\Models\Project::where('project_code', $project_code)->first();
                        if (!$rs) {
                            break;
                        }
                    }
                    $form->project_code = $project_code;

                    // 创建人
                    $currLoginUser = auth('admin')->user();
                    $form->master_user_id = $currLoginUser->id;
                    $form->master_user_name = $currLoginUser->username;
                }
                $form->builder()->pushField(new Form\Field('fee_type'));
                $feeTypeJson = [];
                foreach ($form->fee_type as $v) {
                    $feeTypeJson[$v] = $form->{'fee_type_' . $v};
                }
                $form->fee_type = json_encode($feeTypeJson, '256');
            });

            //
        });
    }
}
